package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.HistoryAlarm;
import com.mingqijia.gassafety.db.entity.WarnStrategy;
import com.mingqijia.gassafety.db.entity.WarningAlarm;
import com.mingqijia.gassafety.db.entity.WarningRecord;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.WarningAlarmMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.user.UserBackend;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import com.mingqijia.gassafety.webserver.request.DisposeRecordRequest;
import com.mingqijia.gassafety.webserver.request.DisposeRequest;
import com.mingqijia.gassafety.webserver.request.WarningDataListRequest;
import com.mingqijia.gassafety.webserver.response.CompanyResponse;
import com.mingqijia.gassafety.webserver.response.DisposeRecordResponse;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.response.WarningDataResponse;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName WarningDataServiceImpl.java
 * @Description 报警数据
 * @createTime 2023年02月09日
 */
@Slf4j
@Service
public class WarningDataServiceImpl extends ServiceImpl<WarningAlarmMapper, WarningAlarm> implements WarningDataService {

    @Autowired
    private WarningRecordService warningRecordService;

    @Autowired
    private WarningAlarmMapper warningAlarmMapper;
    @Autowired
    private FieldTemplateService fieldTemplateService;

    @Autowired
    private EquipmentServiceImpl service;

    @Autowired
    private WarnStrategyServiceImpl warnStrategyService;
    @Autowired
    CompanyServiceImpl companyService;

    @Autowired
    VccAuthoritiesProvider provider;
    @Autowired
    private DtuMapper dtuMapper;

    @Autowired
    CallTaskService taskService;

    @Autowired
    FieldListShowService fieldListShowService;

    @Autowired
    ConfigureHolder holder;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    CommonService commonService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    private final static String split_m = ":";
    public static final String split_f = ";";
    private ExecutorService executor = Executors.newFixedThreadPool(5);
    /**
     * 报警数据列表
     *
     * @param request
     * @return
     */
    @Override
    public PageUtil<WarningDataResponse> warningDataList(WarningDataListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        int templateType = fieldTemplateService.getBySpId(spId);
        if (templateType == 2) {
            request.setCustName(request.getContactName());
            request.setCustAddress(request.getInstallationAddress());
            request.setCustPhone(request.getContactPhone());
        }
        request.setTemplateType(templateType);
        Page<WarnStrategy> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<WarningDataResponse> warningDataResponses = new ArrayList<>();
        List<WarningAlarm> warningAlarms = warningAlarmMapper
                .selectAllWarningAlarm(request.getStartTime(), request.getEndTime(), request.getImei()
                        , request.getEquipmentType(), request.getEquipmentModel(), request.getEquipmentManufacturer()
                        , request.getDisposeStatus(), request.getCustPhone(), request.getCustName()
                        , request.getCustAddress(), spId, templateType, request.getConcentrationSort(), request.getSubsCode(), request.getOrgCode(), request.getCustomerAddress());
        log.info("warningDataList-列表数据：{}", JSONObject.toJSONString(warningAlarms));

        //设备类型名称
        List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKey(
                EquipmentType.DICT_CODE);
        //行业类型名称
        List<DictionaryItemRespDTO> industryTypeDictList = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        //运营商列表
        List<DictionaryItemRespDTO> detectionTypeList = holder.getDictionaryByKey(Constants.DETECTION_TYPE_CODE);
        List<String> query = service.getQueryParams();
        //List<Map<String, String>> customerCode = service.dictMap(null, query, spId);
        List<String> imeis = new ArrayList<>();
        Map<String, Long> idImeiMap = new HashMap<>();
        warningAlarms.forEach(warningAlarm -> {
            String imei = warningAlarm.getIMEI();
            if (imei.contains(EquipmentServiceImpl.split_)) imei = imei.split(EquipmentServiceImpl.split_)[0];
            imeis.add(imei);
        });

        if (!CollectionUtil.isEmpty(imeis)) {
            List<Map<String, Object>> idMaps = dtuMapper.selectStrategyId(imeis);
            if (!CollectionUtil.isEmpty(idMaps)) {
                idMaps.forEach(stringObjectMap -> {
                    idImeiMap.put(stringObjectMap.get("iMEI") + "", Long.parseLong(stringObjectMap.get("id") + ""));
                });
            }
        }
        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap;
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        } else {
            companyNameMap = new HashMap<>();
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap;
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        } else {
            orgSubsCodeMap = new HashMap<>();
        }

        Map<String,AlarmSupplierListVo> suppliersMap = supplierListVos.stream().collect(Collectors.toMap(AlarmSupplierListVo::getAlarmSystemCode, o -> o));
        warningAlarms.forEach(warningAlarm -> {
            WarningDataResponse warningDataResponse = new WarningDataResponse();
            BeanUtils.copyProperties(warningAlarm, warningDataResponse);

            if (org.apache.commons.lang3.StringUtils.isNotEmpty(warningAlarm.getOrgCode()) && orgSubsCodeMap.containsKey(warningAlarm.getOrgCode())) {
                warningDataResponse.setCompanyName(orgSubsCodeMap.get(warningAlarm.getOrgCode()));
            } else {
                if (companyNameMap.containsKey(warningAlarm.getSpId())) {
                    warningDataResponse.setCompanyName(companyNameMap.get(warningAlarm.getSpId()));
                }
            }
            warningDataResponse.setValveInfoId(warningAlarm.getValveInfoId());
            warningDataResponse.setPositionLat(warningDataResponse.getPositionLon()+","+warningDataResponse.getPositionLat());
            warningDataResponse.setIndustryType(dictionaryService.getName(industryTypeDictList, warningAlarm.getIndustryType()));
            warningDataResponse.setEquipmentType(dictionaryService.getName(equipmentTypeDictList, warningAlarm.getEquipmentType()));
            if (!StringUtils.isEmpty(warningAlarm.getEquipmentManufacturer()) && suppliersMap.containsKey(warningAlarm.getEquipmentManufacturer())){
                warningDataResponse.setEquipmentManufacturer(suppliersMap.get(warningAlarm.getEquipmentManufacturer()).getMsName());
            }else {
                warningDataResponse.setEquipmentManufacturer("");
            }
            String[] split = warningAlarm.getDetectionType().split(split_f);
            String str = "";
            str = dictionaryService.getName(detectionTypeList, split[0]);
            warningDataResponse.setDetectionType(str);
            if (warningAlarm.getDisposeStatus() == 0) warningDataResponse.setDisposeStatus("未处理");
            if (warningAlarm.getDisposeStatus() == 1) warningDataResponse.setDisposeStatus("已处理");
            if (warningAlarm.getDisposeStatus() == 2) warningDataResponse.setDisposeStatus("机器人外呼");
            String imei = warningAlarm.getIMEI();
            if (imei.contains(EquipmentServiceImpl.split_)) imei = imei.split(EquipmentServiceImpl.split_)[0];
            if (idImeiMap.containsKey(imei)) warningDataResponse.setStrategyId(idImeiMap.get(imei));
            if(!StringUtils.isEmpty(warningAlarm.getValveInfoId())){
                warningDataResponse.setHasValve("有");
            }else{
                warningDataResponse.setHasValve("-");
            }
            warningDataResponses.add(warningDataResponse);
        });
        List<Integer> consumerIds= warningAlarms.stream().map(WarningAlarm::getConsumerId).collect(Collectors.toList());
        List<Integer> valveInfoIds = warningAlarms.stream().map(WarningAlarm::getValveInfoId).collect(Collectors.toList());
        List<String> iMEIs = warningAlarms.stream().map(WarningAlarm::getIMEI).collect(Collectors.toList());

         commonService.loadFieldAndPackaging(warningDataResponses, WarningDataResponse.class, consumerIds, valveInfoIds, iMEIs, spId, PageListCode.WARNING_DATA.getCode());
        log.info("warningDataListn-warningDataResposes:{}",JSONObject.toJSONString(warningDataResponses));
        List<FieldListShowResponse> responses = fieldListShowService.queryListShowByShowStatus(PageListCode.WARNING_DATA.getCode(), spId);
        List<String> fields = responses.stream().map(FieldListShowResponse::getFieldCode).collect(Collectors.toList());
        List<String> titles = responses.stream().map(FieldListShowResponse::getFieldName).collect(Collectors.toList());
        //区分模板
        List<PageColumns> add = new ArrayList<>();
        if (TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == request.getTemplateType()) {
            add = PageColumnConst.add(PageColumnConst.WarningVccTitles, PageColumnConst.WarningVccIndices);
        } else {
            add = PageColumnConst.add(titles.toArray(new String[]{}), fields.toArray(new String[]{}));
        }
        PageUtil pageInfo = new PageUtil<>(request.getPage(),
                request.getPageSize(), page.getTotal(), warningDataResponses, add);
        return pageInfo;
    }

    /**
     * 处置
     *
     * @param request
     */
    @Override
    public void dispose(DisposeRequest request) {
        log.info("dispose-入参：{}", JSONObject.toJSONString(request));
        List<Long> ids = request.getIds();
        if (CollectionUtils.isEmpty(ids)) throw new BizException("至少选择一条报警数据");
        QueryWrapper<WarningAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(WarningAlarm::getIsDeleted, 0)
                .in(WarningAlarm::getId, ids);
        List<WarningAlarm> warningAlarms = warningAlarmMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(warningAlarms)) throw new BizException("当前数据不存在");
        WarningAlarm warning = warningAlarms.get(0);
        if (request.getDisposeType() == 2 && StringUtils.isEmpty(request.getPushPhones()) &&
                StringUtils.isEmpty(request.getPushConsumers()) &&
                StringUtils.isEmpty(request.getPushStaffs()))
            throw new BizException("请输入至少一种联系方式");
        String callPhones = "";
        String pushStaffs = "";
        String pushConsumers = "";
        if (request.getDisposeType() == 2) {
            callPhones = request.getPushPhones();
            pushStaffs = request.getPushStaffs();
            pushConsumers = request.getPushConsumers();
            if (!StringUtils.isEmpty(callPhones)) {
                if (!callPhones.contains(split_f)) {
                    callPhones = callPhones + ";";
                }
                warnStrategyService.checkPhone(callPhones,0);
            }
            if (!StringUtils.isEmpty(pushStaffs)) {
                if (!pushStaffs.contains(split_f)) pushStaffs = pushStaffs + ";";
                warnStrategyService.checkPhone(pushStaffs,0);
            }
            if (!StringUtils.isEmpty(pushConsumers)) {
                if (!pushConsumers.contains(split_f)) pushConsumers = pushConsumers + ";";
                warnStrategyService.checkPhone(pushConsumers,0);
            }
        }
        if (request.getDisposeType() == 2 &&
                StringUtils.isEmpty(callPhones) &&
                StringUtils.isEmpty(request.getPushConsumers()) &&
                StringUtils.isEmpty(request.getPushStaffs()))
            throw new BizException("请输入至少一种外呼对象");

        WarningAlarm warningAlarm = new WarningAlarm();
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        warningAlarm.setOperatorBy(workingUser.getName() + "(" + workingUser.getUsername() + ")");
        warningAlarm.setPushPhones(callPhones);
        warningAlarm.setPushStaffs(pushStaffs);
        warningAlarm.setPushLevels(pushConsumers);
        warningAlarm.setReason(request.getReason());
        warningAlarm.setDisposeTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        warningAlarm.setDisposeStatus(request.getDisposeType());
        UpdateWrapper<WarningAlarm> wrapper = new UpdateWrapper<>();
        wrapper.lambda().or().in(WarningAlarm::getId, ids)
                .set(WarningAlarm::getPushLevels, warningAlarm.getPushLevels())
                .set(WarningAlarm::getPushPhones, warningAlarm.getPushPhones())
                .set(WarningAlarm::getPushStaffs, warningAlarm.getPushStaffs())
                .set(WarningAlarm::getReason, warningAlarm.getReason())
                .set(WarningAlarm::getDisposeStatus, request.getDisposeType());
        warningAlarmMapper.update(warningAlarm, wrapper);
       String userName= ApplicationUtils.getWorkingUser().getName() + "(" + ApplicationUtils.getWorkingUser().getUsername() + ")";
        if (request.getDisposeType() == 2) {
            log.info("dispose-warning:{}", JSONObject.toJSON(warning));
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    taskService.callTask(warning.getId(), userName);
                }
            });
        }
    }

    /**
     * 处理报警数据
     *
     * @param historyAlarm
     * @param type         0开始 1结束
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleWarningData(HistoryAlarm historyAlarm, int type) {
        log.info("historyAlarm为:{}", historyAlarm);
        String spId = historyAlarm.getSpId();
        QueryWrapper<WarningAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(WarningAlarm::getSpId, spId)
                .eq(WarningAlarm::getIsDeleted, 0)
                .eq(WarningAlarm::getType, 1)
                .eq(WarningAlarm::getIMEI, historyAlarm.getIMEI());
        List<WarningAlarm> warningAlarms = warningAlarmMapper.selectList(queryWrapper);
        log.info("handleWarningData-warningAlarms:{}", JSONObject.toJSONString(warningAlarms));
        WarningAlarm warning = new WarningAlarm();
        if (!CollectionUtil.isEmpty(warningAlarms)) {
            warning = warningAlarms.get(0);
        }
        if (type == 0) {
            WarningAlarm warningAlarm = new WarningAlarm();
            warningAlarm.setIMEI(historyAlarm.getIMEI());
            warningAlarm.setWarningStartTime(DateUtil.format(historyAlarm.getCreatedAt(), DateUtils.DATE_TIME_FORMAT));
            warningAlarm.setConcentration(historyAlarm.getConcentration());
            warningAlarm.setSpId(historyAlarm.getSpId());
            warningAlarm.setType(1);
            if (warning.getId() != null) {
                warning.setType(0);
                warningAlarmMapper.updateById(warning);
            }
            warningAlarm.setAlarmHistoryId(historyAlarm.getId());
            warningAlarmMapper.insert(warningAlarm);
        } else {
            Date date;
            if (StringUtils.isEmpty(warning.getWarningStartTime())){//找不到设备报警发生的时间就取恢复的时间
                date = historyAlarm.getCreatedAt();
            }else {
                date = DateUtil.parse(warning.getWarningStartTime());
            }
            warning.setWarningDuration(getDurationDate(historyAlarm.getCreatedAt(), date));
            warningAlarmMapper.updateById(warning);
        }
    }

    @Override
    public PageUtil<DisposeRecordResponse> getRecordList(DisposeRecordRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        LambdaQueryWrapper<WarningRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarningRecord::getSpId, spId).eq(WarningRecord::getIMEI, request.getIMEI())
                .between(!(StringUtils.isEmpty(request.getStartTime()) && StringUtils.isEmpty(request.getEndTime())),
                        WarningRecord::getWarningStartTime, request.getStartTime(), request.getEndTime())
                .eq(WarningRecord::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(!StringUtils.isEmpty(request.getPushPhone()), WarningRecord::getPushPhone, request.getPushPhone())
                .eq(!StringUtils.isEmpty(request.getNotifyObjType()), WarningRecord::getNotifyObjType, request.getNotifyObjType())
                .orderByDesc(WarningRecord::getCreatedAt);
        Page<WarningRecord> pager = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<WarningRecord> list = warningRecordService.list(queryWrapper);
        List<DisposeRecordResponse> resultList = list.stream().map(warningRecord -> {
            DisposeRecordResponse response = new DisposeRecordResponse();
            BeanUtils.copyProperties(warningRecord, response);
            response.setSendTime(warningRecord.getCreatedAt());
            response.setConcentration(warningRecord.getConcentration() + " %LEL");
            LambdaQueryWrapper<WarningAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WarningAlarm::getId, warningRecord.getTaskIdentificationCode());
            WarningAlarm warningAlarm = this.getOne(wrapper);
            if (warningAlarm != null) {
                response.setDisposeStatus(warningAlarm.getDisposeStatus());
                response.setReason(warningAlarm.getReason());
                response.setDisposeTime(warningAlarm.getDisposeTime());
                response.setWarningDuration(warningAlarm.getWarningDuration());
                response.setReason(warningAlarm.getReason());
                return response;
            }
            return null;
        }).filter(Objects::nonNull).filter(response -> {
            if (!StringUtils.isEmpty(request.getDisposeStatus())) {
                return request.getDisposeStatus().equals(response.getDisposeStatus());
            }
            return true;
        }).collect(Collectors.toList());

        PageUtil<DisposeRecordResponse> pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(),
                pager.getTotal(), resultList);
        return pageInfo;
    }

    @Override
    public PageUtil<WarningDataResponse> warningHistoryList(WarningDataListRequest request) {
        if (StringUtils.isEmpty(request.getImei())) throw new BizException("设备号不能为空");
        String spId = ApplicationUtils.getWorkingSpId();
        Page<WarnStrategy> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<WarningDataResponse> warningDataResponses = new ArrayList<>();
        List<WarningAlarm> warningAlarms = warningAlarmMapper
                .selectAllWarningAlarmHistory(request.getImei(), spId);
        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap;
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        } else {
            companyNameMap = new HashMap<>();
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap;
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        } else {
            orgSubsCodeMap = new HashMap<>();
        }
        log.info("warningDataList-列表数据：{}", JSONObject.toJSONString(warningAlarms));
        warningAlarms.forEach(warningAlarm -> {
            WarningDataResponse warningDataResponse = new WarningDataResponse();
            BeanUtils.copyProperties(warningAlarm, warningDataResponse);
            warningDataResponse.setDisposeStatus("未处理");
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(warningAlarm.getOrgCode()) && orgSubsCodeMap.containsKey(warningAlarm.getOrgCode())) {
                warningDataResponse.setCompanyName(orgSubsCodeMap.get(warningAlarm.getOrgCode()));
            } else {
                if (companyNameMap.containsKey(warningAlarm.getSpId())) {
                    warningDataResponse.setCompanyName(companyNameMap.get(warningAlarm.getSpId()));
                }
            }
            warningDataResponses.add(warningDataResponse);
        });
        PageUtil pageInfo = new PageUtil<>(request.getPage(),
                request.getPageSize(), page.getTotal(), warningDataResponses);
        return pageInfo;
    }

    /**
     * 计算区间间隔 00:00:00
     *
     * @param startDate
     * @param endDate
     */
    public String getDurationDate(Date startDate, Date endDate) {
        String formatBetween = DateUtil.formatBetween(endDate, startDate, BetweenFormatter.Level.SECOND);
        formatBetween = formatBetween.replace(BetweenFormatter.Level.SECOND.getName(), "");
        if (formatBetween.contains(BetweenFormatter.Level.MINUTE.getName())) {
            formatBetween = formatBetween.replace(BetweenFormatter.Level.MINUTE.getName(), split_m);
        } else {
            formatBetween = "00" + split_m + formatBetween;
        }
        if (formatBetween.contains(BetweenFormatter.Level.HOUR.getName())) {
            formatBetween = formatBetween.replace(BetweenFormatter.Level.HOUR.getName(), split_m);
        } else {
            formatBetween = "00" + split_m + formatBetween;
        }
        if (formatBetween.contains(BetweenFormatter.Level.DAY.getName())) {
            formatBetween = formatBetween.substring(formatBetween.indexOf(BetweenFormatter.Level.DAY.getName()), formatBetween.length());
            formatBetween = "59" + formatBetween.substring(formatBetween.indexOf(split_m), formatBetween.length());
        }
        String format = "";
        String[] split = formatBetween.split(split_m);
        for (int i = 0; i < split.length; i++) {
            String s = split[i] + split_m;
            if (s.length() < 3 && s.length() == 2) {
                format = format + "0" + s;
            } else {
                format = format + s;
            }
        }
        if (format.substring(format.length() - 1, format.length()).contains(split_m)) {
            format = format.substring(0, format.length() - 1);
        }
        return format;
    }



}